<template>
	<view>
		<view class="title">企业信息</view>
		<view class="contract-info-box">
			<view class="in-text">
				<view class="itext-word">
					<text style="color: red;">*</text>企业名称
				</view>
				<view class="intext-in">
					<input type="text" :disabled="updataFlag" :style="unitNameCorrect == false ? 'color: red;' : ''"
						v-model="unitName" placeholder="请填写企业名称">
				</view>
			</view>
			<!-- <view class="in-text">
				<view class="itext-word">
					<text style="color: red;">*</text>统一社会信用代码
				</view>
				<view class="intext-in">
					<input type="text" :disabled="updataFlag" :style="societyCodeCorrect == false ? 'color: red;' : ''"
						v-model="unitCreditCode" placeholder="请填写统一社会信用代码">
				</view>
			</view> -->
			<view class="in-text">
				<view class="itext-word">
					<text style="color: red;">*</text>法定代表人/负责人
				</view>
				<view class="intext-in">
					<input type="text" :disabled="updataFlag" :style="unitOwnNameCorrect == false ? 'color: red;' : ''"
						v-model="unitOwnName" placeholder="请填写法定代表人/负责人">
				</view>
			</view>
			<view class="in-text">
				<view class="itext-word">
					<text style="color: red;">*</text>电话
				</view>
				<view class="intext-in">
					<input type="text" :disabled="updataFlag" :style="phoneCorrect == false ? 'color: red;' : ''"
						v-model="unitOwnPhone" placeholder="请填写电话">
				</view>
			</view>
			<!-- <view class="in-text">
				<view class="itext-word">
					<text style="color: red;">*</text>企业属地
				</view>
				<view class="intext-in">
					<input type="text" :disabled="updataFlag" v-model="unitWhere" placeholder="请填写企业属地">
				</view>
			</view>
			<view class="in-text">
				<view class="itext-word">
					所有制性质
				</view>
				<view class="intext-in">
					<picker :disabled="updataFlag" mode="selector" @change="setunitValue($event)" :range="gongsi">
						<view :style="unitValue == '点击选择所有性质' ? 'color: #808080;' : ''">{{unitValue}}</view>
					</picker>
				</view>
			</view>
			<view class="in-text">
				<view class="itext-word">
					注册时间
				</view>
				<view class="intext-in">
					<picker :disabled="updataFlag" mode="date" @change="changeRegisterTime">
						<view :style="unitCreateTime == '点击选择注册时间' ? 'color: #808080;' : ''">{{unitCreateTime}}</view>
					</picker>
				</view>
			</view>
			<view class="in-text">
				<view class="itext-word">
					<text style="color: red;">*</text>投资金额(万元)
				</view>
				<view class="intext-in">
					<input type="text" :disabled="updataFlag" :style="unitQualityCorrect == false ? 'color: red;' : ''"
						v-model="unitQuality" placeholder="请填写投资金额">
				</view>
			</view> -->
		</view>
		<view class="title">附件信息上传（必填）</view>
		<view class="idcard-renzheng" style="margin-top: 15rpx;">
			<view class="imgandtext">
				<view>
					<view class="">公章承诺书</view>
					<view class="" style="color: #afafaf; font-size: 12px;">
						2M以内jpg,jpeg,png格式图片
					</view>
				</view>
				<view class="card-img">
					<!-- <view class="dianzizhang"> -->
					<image :src="bookphoto" @click="subimg2" mode=""></image>
				</view>
			</view>
			<view class="imgandtext">
				<view>
					<view class="">电子章图片</view>
					<view class="" style="color: #afafaf; font-size: 12px;">
						2M以内jpg,jpeg,png格式图片
					</view>
				</view>
				<view class="dianzizhang" style="">
					<image :src="dianziphoto" @click="subimg1"></image>
				</view>
			</view>
		</view>
		<view class="enter-btn" v-if="selectId == null">
			<button @click="addsubcontract()">确认</button>
		</view>
	</view>
</template>

<script>
    import myutil from '../../../common/util.js'
	export default {
		data() {
			return {
				unitOwnNameCorrect: false, //投资人名格式是否正确
				unitQualityCorrect: false, //投资金额格式是否正确
				unitNameCorrect: false, //企业名称格式是否正确
				societyCodeCorrect: false, // 社会信用代码格式是否正确
				dianziphoto: '../../../static/images/dianzizhang.png',
				bookphoto: '../../../static/images/chengnuoshu.png',
				successpath1: '',
				successpath2: '',
				houzhuiming1: '',
				houzhuiming2: '',
				id: 1,
				unitCreateTime: "点击选择注册时间",
				unitCreditCode: "", //统一社会代码
				unitName: "", //企业名称
				unitOwnName: "", //法定代表人/负责人
				unitOwnPhone: "",
				unitPromiseImgOne: "",
				unitPromiseImgTwo: "",
				unitQuality: "", //投资金额
				unitType: 0,
				unitValue: "点击选择所有性质",
				unitWhere: "", //企业属地
				unitWorkWhere: "",
				imglist: [],
				returnImage1: '', //上传公章承诺书返回的路径
				returnImage2: '', //上传电子章图片返回的路径
				gongsi: ['有限责任公司', '股份有限责任公司', '个体工商户', '非公司企业法人', '私营独资企业', '私营合伙企业', '国有企业', '集体所有制', '私营企业', '股份制企业'],
				selectId: null,
				updataFlag: false
			}
		},
		onLoad(options) {
			if (options.selectId != null) {
				this.selectId = options.selectId
				// 从详情点进来
				console.log('从详情点进来');
				let resData = null
				this.updataFlag = true
				uni.$get(this.path + '/unit/get/' + options.selectId).then(res => {
					resData = res.data
					console.log(resData);
					this.unitNameCorrect = true
					this.unitCreditCode = resData.unitCreditCode
					this.unitName = resData.unitName
					this.unitOwnName = resData.unitOwnName
					this.unitCreateTime = resData.unitCreateTime.split(' ')[0]
					this.unitOwnPhone = resData.unitOwnPhone
					this.unitValue = resData.unitValue
					this.unitWhere = resData.unitWhere
					this.unitQuality = resData.unitQuality
					this.bookphoto = resData.unitPromiseImgOne
					this.dianziphoto = resData.unitPromiseImgTwo
				})

				uni.setNavigationBarTitle({
					title: '分包详情'
				})
			}
		},
		computed: {
			phoneCorrect() {
				const regex = /^(13[0-9]|14[5-9]|15[0-35-9]|16[6]|17[0-8]|18[0-9]|19[89])\d{8}$/;
				// return this.unitOwnPhone.length == 11
				return regex.test(this.unitOwnPhone)
			},
			societyCodeCorrect() {
				console.log(this.isValidUSCI(this.unitCreditCode));
				return this.isValidUSCI(this.unitCreditCode)
			}
		},
		watch: {
			unitOwnName(newvalue, oldvalue) {
				// 使用正则表达式来检查是否包含数字或符号
				const namePattern = /^[A-Za-z\u4e00-\u9fa5]+$/;
				this.unitOwnNameCorrect = namePattern.test(this.unitOwnName);
				console.log(this.unitOwnNameCorrect);
			},
      unitCreditCode:{
         handler(newName, oldName){
           let result = this.isValidUSCI(this.unitCreditCode)
           console.log(result)
           this.societyCodeCorrect = result
         },
          immediate: true 
      },
			unitName(newvalue, oldvalue) {
				let regex =
					/^[\u4e00-\u9fa5\u3001\u3002\uff0c\uff1f\uff01\uff1b\uff1a\u201c\u201d\u300a\u300b\uff08\uff09\uff5e\u2014\u2026\u2019\u2018\s]+$/;
				this.unitNameCorrect = regex.test(this.unitName)
				console.log(this.unitNameCorrect);
			},
			unitQuality(newvalue, oldvalue) {
				console.log(!isNaN(parseFloat(this.unitQuality)) && isFinite(this.unitQuality));
				this.unitQualityCorrect = !isNaN(parseFloat(this.unitQuality)) && isFinite(this.unitQuality)
			},
       immediate:true, // watch侦听操作内的函数会立刻被执行
		},
		methods: {


			isValidUSCI(usci) {
				if (typeof usci !== 'string') return false;
				usci = usci.trim();
				// 标准规定的要18位
				if (usci.length !== 18) return false;
				/** 代码-值对应，以此得出C_i */
				const C_i_map = new Map();
				C_i_map.set('0', 0);
				C_i_map.set('1', 1);
				C_i_map.set('2', 2);
				C_i_map.set('3', 3);
				C_i_map.set('4', 4);
				C_i_map.set('5', 5);
				C_i_map.set('6', 6);
				C_i_map.set('7', 7);
				C_i_map.set('8', 8);
				C_i_map.set('9', 9);
				C_i_map.set('A', 10);
				C_i_map.set('B', 11);
				C_i_map.set('C', 12);
				C_i_map.set('D', 13);
				C_i_map.set('E', 14);
				C_i_map.set('F', 15);
				C_i_map.set('G', 16);
				C_i_map.set('H', 17);
				C_i_map.set('J', 18);
				C_i_map.set('K', 19);
				C_i_map.set('L', 20);
				C_i_map.set('M', 21);
				C_i_map.set('N', 22);
				C_i_map.set('P', 23);
				C_i_map.set('Q', 24);
				C_i_map.set('R', 25);
				C_i_map.set('T', 26);
				C_i_map.set('U', 27);
				C_i_map.set('W', 28);
				C_i_map.set('X', 29);
				C_i_map.set('Y', 30);

				/** 根据公式计算Ci * Wi的值的列表，总共17个值，以此来计算第18个值 */
				const list = new Array(17).fill(0);
				for (let i = 0; i < 17; i++) {
					const C = C_i_map.get(usci[i]);
					// 不在序列里的话，直接返回false
					if (isNaN(C)) return false;
					const W = Math.pow(3, i) % 31;
					list[i] = C * W;
				}
				// 计算级数之和
				const sum = list.reduce((prev, curr) => prev + curr);
				// 求出校验码字符值
				let C_18 = 31 - (sum % 31);
				if (C_18 === 31) {
					C_18 = 0;
				}
				// 根据校验码字符值，根据map，得到第18位的字符
				let val_18 = null;
				for (let [key, value] of C_i_map.entries()) {
					if (value === C_18) {
						val_18 = key;
					}
				}
				return val_18 === usci[17];
			},

			changeRegisterTime(e) {
				const today = new Date();
				const parsedDate = new Date(e.detail.value);
				if (parsedDate > today) {
					uni.showToast({
						title: '注册时间不能选择未来!',
						icon: 'none'
					})
					return
				}
				console.log(e.detail.value);
				this.unitCreateTime = e.detail.value
			},
			setunitValue(e) {
				this.unitValue = this.gongsi[e.detail.value]
			},
			subimg1() {
				if (this.selectId != null) {
					uni.previewImage({
						count: 1,
						urls: [this.dianziphoto]
					})
					return
				}
				uni.chooseImage({
					count: 1,
					success: (res) => {
						console.log('subimg1', res);
						this.dianziphoto = res.tempFilePaths[0];
						//       console.log('this.dianziphoto',this.dianziphoto);
						// this.houzhuiming1=res.tempFilePaths[0]+'/'+res.tempFiles[0].name
						//       console.log('this.houzhuiming1',this.houzhuiming1);
						//       this.houzhuiming1 = this.houzhuiming1.substr(5,this.houzhuiming1.length)
						//       console.log('this.houzhuiming1',this.houzhuiming1);
						// this.dianziphoto = this.houzhuiming1
						uni.uploadFile({
							url: this.path + '/unit/upload',
							filePath: this.dianziphoto,
							name: 'file',
							header: {
								'Authorization': uni.getStorageSync('token')
							},
							success: (res) => {
								console.log('后端返回', res);
								if (res.statusCode == 200) {
									res.data = res.data.replace(/\r/g, '')
									console.log('res.data', JSON.parse(res.data));
									this.returnImage1 = JSON.parse(res.data).data //$返回字段后无filePath
									this.returnImage1 = JSON.parse(res.data).data //$返回字段后无filePath
									console.log('图片上传1', this.returnImage1);
									// this.dianziphoto =  res.data.filePath
									// this.imglist.push(res.data.filePath)
								}
							},
							fail() {
								uni.hideLoading()
								uni.showModal({
									title: '上传失败'
								})
							}
						})
					}
				})
			},
			subimg2() {
				if (this.selectId != null) {
					uni.previewImage({
						count: 1,
						urls: [this.bookphoto]
					})
					return
				}
				uni.chooseImage({
					count: 1,
					success: (res) => {
						console.log(res);
						this.bookphoto = res.tempFilePaths[0];
						// this.houzhuiming2=res.tempFilePaths[0]+'/' + res.tempFiles[0].name
						//       this.houzhuiming2 = this.houzhuiming2.substr(5,this.houzhuiming2.length)
						console.log('上传', this.dianziphoto);
						uni.uploadFile({
							url: this.path + '/unit/upload',
							filePath: this.bookphoto,
							name: 'file',
							header: {
								'Authorization': uni.getStorageSync('token')
							},
							success: (res) => {
								if (res.statusCode == 200) {
									console.log('后端返回', res);
									uni.hideLoading()
									res.data = res.data.replace(/\r/g, '')
									console.log('res.data', JSON.parse(res.data));
									this.returnImage2 = JSON.parse(res.data).data
									console.log('this.returnImage2', this.returnImage2);
									// this.bookphoto = this.returnImage2
									// this.imglist.push(res.data.filePath)
								}
							},
							fail(err) {
								console.log(err);
								uni.hideLoading()
								uni.showModal({
									title: '提示',
									content: '文件上传失败'
								})
							}
						})
					}
				})
			},
			gettime() {
				//获取当前时间，并更新
				var now = new Date();
				var year = now.getFullYear();
				var month = now.getMonth() + 1;
				var day = now.getDate();
				var hour = now.getHours();
				var minute = now.getMinutes();
				var miao = now.getSeconds()
				var nowdate = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + miao;
				return nowdate;
			},
			addsubcontract() {
				let flag = false;
				// this.societyCodeCorrect.length == 0 ||
				// this.unitQuality.length == 0 ||
				// this.unitWhere.length == 0 ||
				if ( this.unitOwnName.length == 0 || 
					 this.phoneCorrect.length == 0) {
					uni.showToast({
						title: '请填写所有带星号的字段!',
						icon: 'none'
					})
					return
				}

				if (!this.unitOwnNameCorrect) {
					uni.showToast({
						title: '人名不应包含数字和字符',
						icon: 'none'
					})
					return
				}
				// if (!this.unitQualityCorrect) {
				// 	uni.showToast({
				// 		title: '投资金额请填写数字',
				// 		icon: 'none'
				// 	})
				// 	return
				// }
				if (!this.unitNameCorrect) {
					uni.showToast({
						title: '企业名称只允许出现中文和中文字符',
						icon: 'none'
					})
					return
				}
				// if (!this.societyCodeCorrect) {
				// 	uni.showToast({
				// 		title: '统一社会信用代码有误!',
				// 		icon: 'none'
				// 	})
				// 	return
				// }

				// if (this.unitCreateTime == '点击选择注册时间') {
				// 	uni.showToast({
				// 		title: '请点击选择注册时间!',
				// 		icon: 'none'
				// 	})
				// 	return
				// }
				// if (this.unitValue == '点击选择所有性质') {
				// 	uni.showToast({
				// 		title: '请点击选择所有性质!',
				// 		icon: 'none'
				// 	})
				// 	return
				// }

				if (!this.phoneCorrect) {
					uni.showToast({
						title: '电话号码格式有误!',
						icon: 'none'
					})
					return
				}

				if (this.dianziphoto == '../../../static/images/dianzizhang.png' || this.bookphoto ==
					'../../../static/images/chengnuoshu.png') {
					uni.showToast({
						title: '请上传承诺书或电子章图片!',
						icon: 'none'
					})
					return
				}

        if(this.dianziphoto == '../../../static/images/style.jpg' || this.bookphoto == '../../../static/images/chengnuoshu.png'){
          uni.showToast({
            title: '请上传承诺书或电子章图片!',
            icon: 'none'
          })
          return  
        }
        
        
				uni.showLoading({
					title: '上传中'
				})

				uni.$put(this.path + '/unit/addTwo', {
					id: 1,
					unitCreateTime: this.gettime(),
					unitCreditCode: this.unitCreditCode,
					unitName: this.unitName,
					unitOwnName: this.unitOwnName,
					unitOwnPhone: this.unitOwnPhone,
					unitQuality: this.unitQuality,
					unitType: 0,
					unitValue: this.unitValue,
					unitWhere: this.unitWhere,
					unitWorkWhere: this.unitWorkWhere,
					unitPromiseImgOne: this.returnImage2,//$顺序已修改
					unitPromiseImgTwo: this.returnImage1
				}).then(res => {
					console.log('添加分包单位返回值res', res);
					if (res.code == 200) {
						uni.showToast({
							title: '添加成功',
							icon: 'none'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						uni.showModal({
							title: '添加失败，请重试',
              content: res.message
						})
					}
				})
        
        
			}
		}
	}
</script>

<style lang="scss" scoped>
	.enter-btn {
		margin-top: 30rpx;
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;

		button {
			width: 80%;
			background-color: #2f67ff;
			height: 35px;
			line-height: 35px;
			color: white;
			font-size: 14px;
		}
	}

	.idcard-renzheng {
		width: 95%;
		margin: 0 auto;
		height: 420rpx;
		background-color: white;
		border-radius: 10rpx;
		display: flex;
		justify-content: space-around;
		flex-direction: column;

		.imgandtext {
			width: 95%;
			height: 45%;
			margin: 0 auto;
			font-size: 14px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.it-text {
				width: fit-content;
			}

			.card-img {
				width: 45%;
				height: 90%;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.dianzizhang {
				margin-right: 50rpx;
				width: 25%;
				height: 90%;

				image {
					width: 100%;
					height: 100%;
				}
			}
		}
	}

	.title {
		width: 95%;
		margin: 0 auto;
		margin-top: 5px;
		height: 20px;
		line-height: 20px;
		font-size: 15px;
		border-left: 4px solid #2f67ff;
		padding-left: 0.855%;
		box-sizing: border-box;
		color: black;
	}

	.contract-info-box {
		border-radius: 8px;
		background-color: white;
		margin: 0 auto;
		margin-top: 10px;
		width: 95%;

		.xuanxangka {
			width: 90%;
			margin: 0 auto;
			height: 25px;
			display: flex;
			align-items: center;

			.card {
				width: 35%;
				height: 100%;
				text-align: center;
				line-height: 25px;
				font-size: 14px;
				display: flex;
				justify-content: center;
				align-items: center;

				.icon {
					width: 15px;
					height: 15px;
					line-height: 15px;
					text-align: center;
					border-radius: 50%;
					border: 1px solid #bfbfbf;
					color: #bfbfbf;
					font-size: 10;
				}
			}
		}

		.picker-box {
			width: 95%;
			height: 120px;
			background-color: #f6f6f6;
			margin: 0 auto;
			margin-top: 10px;
			margin-bottom: 10px;
			padding-top: 10px;

			.picker-list {
				width: 95%;
				margin: 0 auto;
				display: flex;
				justify-content: space-around;
				align-items: center;
				font-size: 14px;

				.picker-x {
					padding: 5px;
					width: 35%;
					height: 25px;
					background-color: white;
					display: flex;
					justify-content: space-between;
					align-items: center;
				}
			}
		}

		.in-text {
			display: flex;
			width: 95%;
			height: 35px;
			margin: 0 auto;
			justify-content: space-between;
			align-items: center;
			font-size: 14px;
			border-bottom: #f6f9fc 1px solid;

			.itext-word {
				width: fit-content;
			}

			.intext-in {
				width: 60%;

				picker {
					float: right;
				}

				.bianxin {
					transform: scale(0.8);
					font-size: 13px;
					float: right;
				}

				input {
					width: 100%;
					font-size: 13px;
					text-align: right;
				}
			}

		}

		.xuanxangbox {
			width: 95%;
			margin: 0 auto;
			height: 80px;
			display: flex;
			justify-content: space-around;
			align-items: center;
			border-bottom: #f6f9fc 1px solid;

			.xuanxang {
				width: 30%;
				height: 50px;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 12px;
				background-color: #f6f6f6;
				color: #bfbfbf;
			}
		}

		.text-box {
			width: 95%;
			margin: 0 auto;
			height: 120px;

			textarea {
				width: 100%;
				height: 100px;
				background: #f6f6f6;
				font-size: 14px;
			}

			.totalnum {
				background: #f6f6f6;
				width: 100%;
				text-align: right;
				font-size: 12px;
				color: #bfbfbf;
			}
		}
	}
</style>